package ws

import (
	"context"
	"encoding/json"
	"poker/env"

	"sync"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/nlh1996/utils"
)

// ConnPool .
type ConnPool struct {
	pool map[string]*Connection
	sync.RWMutex
}

var instance *ConnPool

// GetConnPool .
func GetConnPool() *ConnPool {
	if instance == nil {
		instance = &ConnPool{}
		instance.pool = make(map[string]*Connection, env.GlobalData.Conn.PoolConnNum)
	}
	return instance
}

// 发送心跳包，一次编码
func init() {
	var ping = gin.H{"status": 100, "data": "Ping"}
	msgBytes, err := json.Marshal(ping)
	if err != nil {
		return
	}
	var callback = func() {
		for _, v := range GetConnPool().pool {
			v.SendJSON(msgBytes)
		}
	}
	go utils.Timer(callback, time.Minute*1, -1, context.Background())
}

// GetConnByID .
func (p *ConnPool) GetConnByID(id string) *Connection {
	p.Lock()
	defer p.Unlock()
	if v, ok := p.pool[id]; ok {
		return v
	}
	return nil
}

// Set .
func (p *ConnPool) Set(c *Connection) {
	p.Lock()
	defer p.Unlock()
	p.pool[c.ID] = c
}

// DelByID .
func (p *ConnPool) DelByID(id string) {
	p.Lock()
	defer p.Unlock()
	delete(p.pool, id)
}
